package football.haha.com.footballtv.activity;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer;

import butterknife.Bind;
import butterknife.ButterKnife;
import football.haha.com.footballtv.R;
import football.haha.com.footballtv.utils.Tools;
import football.haha.com.footballtv.view.EmptyControlVideo;
import football.haha.com.footballtv.view.VideoView;

/**
 * Created by oo on 2017/10/16.
 */

public class PlayActivity extends BaseActivity {

    public static final int KeyHideControl = 1000;
    public static final int KeyPlayProgress = 1001;

    @Bind(R.id.tv_play_type)
    TextView tvPlayType;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.cb_playTag)
    CheckBox cbPlayTag;
    @Bind(R.id.tv_time_left)
    TextView tvTimeLeft;
    @Bind(R.id.sb_play_progress)
    SeekBar sbPlayProgress;
    @Bind(R.id.tv_time_right)
    TextView tvTimeRight;
    @Bind(R.id.rl_control)
    RelativeLayout rlControl;
    @Bind(R.id.rl_time_info)
    RelativeLayout rlTimeInfo;
    @Bind(R.id.ll_loading)
    LinearLayout llLoading;
    @Bind(R.id.fl_content)
    FrameLayout flContent;
    @Bind(R.id.tv_time_tag)
    TextView tvTimeTag;
    @Bind(R.id.ijk_video_player)
    EmptyControlVideo mIjkVideoPlayer;
    @Bind(R.id.videoview_source)
    android.widget.VideoView videoviewSource;

    VideoView mVlcVideoPlayer;

    long videoLength = 0;

    private int videoType = 0; //0是点播  1是直播
    private String url = "http://mirror.aarnet.edu.au/pub/TED-talks/911Mothers_2010W-480p.mp4";

    Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == KeyHideControl) {
                if (rlControl.getVisibility() == View.VISIBLE) {
                    rlControl.setVisibility(View.GONE);
                    tvTimeTag.setVisibility(View.GONE);
                } else {
                    rlControl.setVisibility(View.VISIBLE);
                }
            } else if (msg.what == KeyPlayProgress) {
                myHandler.sendEmptyMessageDelayed(KeyPlayProgress, 1000);

                videoLength = mVlcVideoPlayer.libvlc.getLength() / 1000;
                long time = mVlcVideoPlayer.libvlc.getTime() / 1000;

                tvTimeRight.setText(Tools.secToTime(videoLength));
                tvTimeLeft.setText(Tools.secToTime(time));
                if (videoLength > 10 && !sbPlayProgress.isFocused()) {
                    sbPlayProgress.setProgress((int) (time * 100.0 / videoLength));
                }
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play);
        ButterKnife.bind(this);

        initView();
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mIjkVideoPlayer!=null){
            mIjkVideoPlayer.release();
        }

    }

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            showToast("再按一次退出播放");
            //并记录下本次点击“返回键”的时刻，以便下次进行判断
            mExitTime = System.currentTimeMillis();
        } else {
            //释放所有
            if (videoType == 1 && mIjkVideoPlayer!=null) {
                mIjkVideoPlayer.setStandardVideoAllCallBack(null);
                GSYVideoPlayer.releaseAllVideos();
            }
            finish();
        }
    }

    private void initView() {
        String videoName = getIntent().getStringExtra("videoName");
        tvTitle.setText(videoName);

        videoType = getIntent().getIntExtra("videoType", 0);
        url = getIntent().getStringExtra("PlayUrl");
////        url = "http://103.251.84.180:2066/null/PPTV-000000000000000000000006248/filename.m3u8?owchid=vod&Contentid=PPTV-000000000000000000000006248&&token=94A75F748268DDEB395C65D70F073E174DEAEAC95DBDDEBCDF06EDB4F4DFA81A5F1BB1A138A9BC782EB5298C9E6096CBFC2BBD9F376286D9B320501313FF69C74EC8EFEA61DF6DEC87AD03B6C19D220DE92B5C8572B11178796EAF940C94998556586C0AFB2369CD937141C5FD832A8A04BCCDB781AA3261EDA384CACD483BBF7AB1DF528A06BADE9BCE3276AD575DEA41786FE0E95144279E5A369998AAEDE36055B975A15DA9ED45301B789C9B1DE1FF25E3094F332C48A98DD3C0DF1ADEBBF6&isHD=0&isIpqam=0&Contentid=PPTV-000000000000000000000006248";
////        url = "http://103.251.84.180:2063/live.m3u8?Contentid=live2&owchid=live";
//        if (TextUtils.isEmpty(url)){
////            url = "http://devimages.apple.com/iphone/samples/bipbop/gear1/prog_index.m3u8";
//            showToast("播放地址PlayUrl为空");
//            return;
//        }else{
////            showToast("播放地址PlayUrl  "  + url);
//        }
//        videoType = 1;
//        url = "rtsp://10.21.4.238:5544/nn_vod.ts?id=2e573b8525a9e3d7fa177bdddaeaa293&nn_area_code=30130&provider=coship&nst=ipqam&npv=gz_starcor&did=01010216082401000234&uid=01010216082401000234";

//        url = "http://mirror.aarnet.edu.au/pub/TED-talks/911Mothers_2010W-480p.mp4";

        videoviewSource.setVideoPath(url);
        videoviewSource.setVisibility(View.VISIBLE);
        videoviewSource.start();

        if (videoType == 0) {
            tvPlayType.setText("回看");
            rlTimeInfo.setVisibility(View.VISIBLE);
//            DisplayMetrics metrics = new DisplayMetrics();
//            getWindowManager().getDefaultDisplay().getMetrics(metrics);
//
//            mVlcVideoPlayer = new VideoView(this, url);
//            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(metrics.widthPixels, metrics.heightPixels);
//            mVlcVideoPlayer.setLayoutParams(params);
//            flContent.addView(mVlcVideoPlayer, 0);
//
//            myHandler.sendEmptyMessageDelayed(KeyPlayProgress, 1000);

        } else {
            tvPlayType.setText("直播");
            rlTimeInfo.setVisibility(View.GONE);
//            mIjkVideoPlayer.setVisibility(View.VISIBLE);
//            mIjkVideoPlayer.setUp(url, true, "");
//            mIjkVideoPlayer.startPlayLogic();
        }

        tvTimeTag.setVisibility(View.GONE);
        llLoading.setVisibility(View.GONE);
        myHandler.sendEmptyMessageDelayed(KeyHideControl, 5000);
        sbPlayProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                setTvTimeTagInfo(i);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });


    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
            myHandler.sendEmptyMessageDelayed(KeyHideControl, 5000);
            if (videoType == 0) {
                mVlcVideoPlayer.libvlc.setTime(sbPlayProgress.getProgress() * videoLength * 1000 / 100);
            }
        } else if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) {
            if (videoType == 0) {
                if (mVlcVideoPlayer.libvlc.isPlaying()){
                    mVlcVideoPlayer.libvlc.pause();
                    cbPlayTag.setChecked(false);
                }else{
                    mVlcVideoPlayer.libvlc.play();
                    cbPlayTag.setChecked(true);
                }
            } else {
                if (mIjkVideoPlayer!=null){
                    if (mIjkVideoPlayer.getCurrentPlayer().getCurrentState()==5){
                        mIjkVideoPlayer.getCurrentPlayer().onVideoResume();
                        cbPlayTag.setChecked(true);
                    }else{
                        mIjkVideoPlayer.getCurrentPlayer().onVideoPause();
                        cbPlayTag.setChecked(false);
                    }
                }
            }
        }
        myHandler.sendEmptyMessageDelayed(KeyHideControl, 5000);
        if (sbPlayProgress.isFocused()){
            tvTimeTag.setVisibility(View.VISIBLE);
        }else{
            tvTimeTag.setVisibility(View.GONE);
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        rlControl.setVisibility(View.VISIBLE);
        myHandler.removeMessages(KeyHideControl);
        return super.onKeyDown(keyCode, event);
    }

    private void setTvTimeTagInfo(int progress) {
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams((int) getResources().getDimension(R.dimen.px250),
                (int) getResources().getDimension(R.dimen.px110));
        int[] location = new int[2];
        sbPlayProgress.getLocationOnScreen(location);
        params.topMargin = location[1] - (int) getResources().getDimension(R.dimen.px115);
        params.leftMargin = (int) (location[0] + (sbPlayProgress.getWidth() - sbPlayProgress.getPaddingEnd() - sbPlayProgress.getPaddingStart()) * progress / 100.0f
                - getResources().getDimension(R.dimen.px125) + 27);
        tvTimeTag.setLayoutParams(params);
        tvTimeTag.setVisibility(View.VISIBLE);

        tvTimeTag.setText(Tools.secToTime(progress * videoLength / 100));
    }

}
